﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Xml;

using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Server;
using Microsoft.TeamFoundation.WorkItemTracking.Client;


namespace Sogeti.QueryWrapper
{



    public class WiqlFolder
    {
        public string Name;
        public string Path;

        public Dictionary<string, string> queries;
        public WiqlFolder()
        {
            queries = new Dictionary<string, string>();
        }

    }

    public class TPQueryWrapper
    {
        protected TfsTeamProjectCollection tpCollection;
        protected WorkItemStore wiStore;
        protected QueryHierarchy qh;
        protected CommonStructureWrapper css;


        public TPQueryWrapper(string tpCollectionUrl, string teamProjectName)
        {
            tpCollection = new TfsTeamProjectCollection(new Uri(tpCollectionUrl));
            wiStore = (WorkItemStore)tpCollection.GetService(typeof(WorkItemStore));
            qh = wiStore.Projects[teamProjectName].QueryHierarchy;
            css = new CommonStructureWrapper(tpCollectionUrl);


        }

        public string GetFirstIteration(string teamProjectName)
        {
            XmlElement xmlIteratios= css.GetNodesTree(StructureType.Iteration, teamProjectName);

            string firstIterationPath="";
            firstIterationPath = FindFirstNode(xmlIteratios.ChildNodes[0]);
            return firstIterationPath;

        }
        private String FindFirstNode(XmlNode startNode)
        {
            if(startNode.HasChildNodes){
                return FindFirstNode(startNode.ChildNodes[0]);
    
            }
            else
            {
                return startNode.Attributes["Path"].Value.ToString();
            }
        }

        public WiqlFolder FindFolderWithFilter(string filter, bool allQueriesFiltered)
        {

            foreach(QueryFolder fld in qh)
            {
                WiqlFolder wiqlFld = FindFolderWithFilter(fld, filter, allQueriesFiltered);
                if (wiqlFld !=null )
                {
                    return wiqlFld;
                }
            }
            return null;
        }
        public WiqlFolder FindFolderWithFilter(QueryFolder fld, string filter, bool allQueriesFiltered)
        {
            bool filterFound = false;
            bool allFiltered = true;

            WiqlFolder wiqlFld = new WiqlFolder{Name=fld.Name, Path=fld.Path};


            foreach (QueryItem itm in fld){
                if (itm.GetType() == typeof(QueryFolder)){
                    return FindFolderWithFilter((QueryFolder)itm, filter, allQueriesFiltered);
                }
                else{
                    string sWIql = ((QueryDefinition)itm).QueryText;
                    wiqlFld.queries.Add(itm.Name, sWIql);

                    if (sWIql.IndexOf(filter)>=0)
                    {
                        filterFound = true;
                    }
                    else{
                           allFiltered=false;
                    }

                }
            }
            
            if( filterFound && allQueriesFiltered && allFiltered){              
                return wiqlFld;
            }
            else{
                return null;
            }

        }


        protected QueryFolder FindFolder(string path, QueryFolder fld)
        {
            
            string fldName = path;

            if(path.IndexOf(@"/")>0)
            {
                fldName = path.Substring(0, path.IndexOf(@"/"));
            }
           
            
            if (fld.Contains(fldName))
            {
                if(path.IndexOf(@"/")>0){
                        return FindFolder(path.Substring(path.IndexOf(@"/")+1), (QueryFolder)fld[fldName]);
                }else{
                    return (QueryFolder)fld[fldName];
                }
            }
            else
            {
                return null;
            }


       }


        public void SaveQueryFolder(WiqlFolder wiqlFLd)
        {
             
            string path = wiqlFLd.Path.Substring(wiqlFLd.Path.IndexOf(@"/")+1);
            

            QueryFolder fld = FindFolder(path, qh);
            if(fld==null){

                QueryFolder fldParent= FindFolder(path.Substring(0, path.LastIndexOf(@"/")), qh);
 

                fld=new QueryFolder(wiqlFLd.Name);
                fldParent.Add(fld);
            }

            

            foreach (KeyValuePair<string, string> qry in wiqlFLd.queries)
            {
                QueryDefinition itmTarget = null;
                if(fld.Contains(qry.Key))
                {
                    itmTarget = (QueryDefinition)fld[qry.Key];
                    itmTarget.QueryText = qry.Value;
                }
                else{
                    itmTarget = new QueryDefinition(qry.Key, qry.Value);
                    fld.Add(itmTarget);
                }

            }

            qh.Project.Store.RefreshCache(); // Force refresh on Iterations & areas to avoid error in save
            qh.Save();
        }

#region "oldstuf"    
        public void CopyFolder(String sourceFolder, string targetFolder, string search, string replace)
        {

            foreach (QueryFolder fld in qh)
            {
                CopyFolder(fld,sourceFolder, targetFolder, search, replace );
            }
        }

        public void CopyFolder(QueryFolder fldRoot, String sourceFolder, string targetFolder, string search, string replace)
        {

            foreach (QueryItem fld in fldRoot)
            {
                if (fld.GetType() == typeof(QueryFolder))
                {
                    if (fld.Name == sourceFolder)
                    {
                        QueryFolder fldTarget = new QueryFolder(targetFolder);
                        fld.Parent.Add(fldTarget);

                        CopyFolder((QueryFolder)fld, fldTarget,  search, replace);
                        qh.Save();
                    }
                }
            }
        }
        private static void CopyFolder(QueryFolder fld, QueryFolder fldTarget, string search, string replace)
        {
            foreach (QueryItem itm in fld)
            {
                if (itm.GetType() == typeof(QueryFolder))
                {
                    QueryFolder newFolder = new QueryFolder(itm.Name);
                    fldTarget.Add(newFolder);
                    CopyFolder((QueryFolder)itm, newFolder, search, replace);

                }
                else
                {
                    string sWIql = ((QueryDefinition)itm).QueryText;
                    if(search!= String.Empty  && replace!=String.Empty)
                    {
                        sWIql= sWIql.Replace(search, replace);
                    }
                    QueryDefinition itmTarget = new QueryDefinition(itm.Name, sWIql);
                    fldTarget.Add(itmTarget);

                }
            }

        }
#endregion
    }
}